package com.shen.cloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.shen.cloud.pojo.Department;
import com.shen.cloud.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DepartmentController {
    @Autowired
    DepartmentService departmentService;

    @PostMapping("/dept/add")
    public boolean insertDepartment(Department department){
        return departmentService.insertDepartment(department);
    }


    /**
     * 当方法调用返回为null时调用其他方法，
     *
     */

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod ="hystrix_selectDepartmentById" )  //熔断后调用的方法
    public Department selectDepartmentById(@PathVariable("id") Long id){
        Department department = departmentService.selectDepartmentById(id);
        if(department==null){
            throw new RuntimeException("id====>"+id+",不存在该用户，或者信息无法找到~");
        }
        return department;
    }

    //备选方法
    public Department hystrix_selectDepartmentById(@PathVariable("id") Long id){
        return new Department()
                .setId(id)
                .setName("id===>"+id+",不存在该用户，或者信息无法找到~")
                .setDbSource("no database in mysql");
    }


    @GetMapping("/dept/list")
    public List<Department> selectAllDepartment(){
        return departmentService.selectAllDepartment();
    }
}
